<template>
  <div>
    <div class="app-page">
      <!-- <div class="content"> -->
      <table-search
        ref="TableSearch"
        :search-form="queryFormItem"
        :on-submit="handleQuery"
        :on-reset="handleRest"
      >
        <div slot="new-add-button" style="line-height:45px">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAdd"
          >
            添加账号
          </el-button>
        </div>
      </table-search>
      <!-- </div> -->
    </div>
    <div class="banner">
      <el-card class="left">
        <!-- <tree :form-data="treeData" :handle-tree="handleTree" /> -->
        <el-tree
          ref="tree"
          :load="loadNode"
          :props="treeProps"
          :default-expanded-keys="defaultExpanded"
          node-key="id"
          lazy
          @node-click="handleTree"
        />
      </el-card>
      <el-card class="right">
        <TablePaging
          :table-list="deviceList"
          border
          :table-column="deviceTableColumn"
          :table-buttons="deviceTableButtons"
          :table-btn-width="180"
          :table-paging="deviceTablePaging"
          :table-total="deviceTableTotal"
          @pagingChange="handlePaginChange"
        />
      </el-card>
    </div>
    <!--       :before-close="handleCancle" -->
    <device-update
      ref="deviceUpdate"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :handle-submit-f="handleModalSubmit"
      :form-data="modalFormData"
      :device-code-disabled="deviceCodeDisabled"
    />
  </div>
</template>

<script>
// 删除OK，添加账号接口有问题，编辑接口-传ID 后台给数据，停用目前没有
import {
  accountFindPage,
  accountDelete,
  accountUpdateStatus
} from '@/api/accountManage'
import { accountAdd, accountUpdate, accountGet } from '@/api/account'
import { commonGetDeptTree, selectDeptList } from '@/api/common/commonDropDown'
import { TableSearch, TablePaging } from '@/components'
import DeviceUpdate from './update'
import { queryFormItem, tableColumn } from './config'
// import { formatTree } from '@/utils/index'
export default {
  components: { TableSearch, DeviceUpdate, TablePaging },
  data() {
    return {
      inputValue: '',
      queryFormData: {},
      queryFormItem: queryFormItem(this.changeLocation),
      deviceTableColumn: tableColumn(1, 10),
      deviceList: [],
      deviceTableButtons: [
        // 设备表操作按钮
        {
          name: '编辑',
          click: this.handleEdit
        },
        {
          name: scope => (scope.row.status === 1 ? '停用' : '启用'),
          authKey: 'b_1_4',
          click: (id, row) =>
            this.handleUpdateStatus(id, row.status === 1 ? 2 : 1)
        },
        {
          name: '删除',
          confirm: '确认删除？',
          click: this.handleDelete
        }
      ],

      deviceTableTotal: 0,
      deviceTablePaging: {
        page: 1,
        pagesize: 10
      },
      dialogTitle: '添加', // 弹窗标题
      dialogVisible: false, // 弹窗显示隐藏
      modalFormData: {}, // 弹窗表单数据
      deviceCodeDisabled: false, // 设备号是否禁止修改
      treeData: [], // 树形结构数据
      treeProps: {
        label: 'name',
        id: 'id',
        isLeaf: data => {
          return data.parentDeptId !== 0
        },
        children: []
      },
      defaultExpanded: []
    }
  },
  watch: {
    // modalFormData: {
    //   handler(newValue, oldValue) {
    //     console.log(newValue)
    //     console.log(oldValue)
    //     console.log(this.modalFormData)
    //   },
    //   immediate: true
    // }
  },
  created() {
    this.postFindPage()
  },
  methods: {
    handleQuery(values) {
      // 查询点击
      this.queryFormData = values
      this.deviceTablePaging = {
        page: 1,
        pagesize: 10
      }
      this.postFindPage()
    },
    handleRest(values) {
      this.queryFormData = values
      this.deviceTablePaging = {
        page: 1,
        pagesize: 10
      }
      this.queryFormItem.forEach(obj => {
        for (const key in obj) {
          if (obj[key] === 'deptId') {
            this.$set(obj, 'options', {})
          }
        }
      })
      this.postFindPage()
    },

    handleAdd() {
      // 新增
      // name: '1', accountType: 1
      this._setModalData('添加账号', true, {})
    },

    // 编辑
    handleEdit(id) {
      console.log(id)
      accountGet({ id }).then(res => {
        this._setModalData('编辑账号', true, res)
      })
    },

    handleDelete(id) {
      // 点击删除
      this.postDeviceDelete(id)
    },

    handleModalSubmit(values, addOrEdit) {
      if (addOrEdit.addOrEdit) {
        accountAdd(values).then(res => {
          this.dialogVisible = false
          this.$message({
            type: 'success',
            message: '添加成功'
          })
          this.postFindPage()
        })
      } else {
        accountUpdate(values).then(res => {
          this.dialogVisible = false
          this.$message({
            type: 'success',
            message: '编辑成功'
          })
          this.postFindPage()
        })
      }
    },

    handlePaginChange(pageInfo) {
      // 分页改变
      this.deviceTablePaging = pageInfo
      this.postFindPage()
      const { page, pagesize } = pageInfo
      this.deviceTableColumn = tableColumn(page, pagesize)
    },

    _setModalData(title = '添加账号', visible = true, formData = {}) {
      // 设置弹窗
      this.modalFormData = formData
      this.dialogTitle = title
      this.dialogVisible = visible
      this.deviceCodeDisabled = title !== '添加'
    },

    postFindPage() {
      // 获取列表
      accountFindPage({
        ...this.queryFormData,
        ...this.deviceTablePaging
      }).then(res => {
        const { records, current, size, total } = res
        this.deviceList = records
        this.deviceTablePaging = {
          page: current,
          pagesize: size
        }
        this.deviceTableTotal = total
      })
    },

    postDeviceAdd(values) {
      // 设备新增
      accountAdd({ ...values }).then(res => {
        this.dialogVisible = false
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.postFindPage()
      })
    },

    postDeviceUpdate(values) {
      // 设备更新
      accountUpdate({ orgId: 1, ...values }).then(() => {
        this.dialogVisible = false
        this.$message({
          type: 'success',
          message: '修改成功'
        })
        this.postFindPage()
      })
    },

    postDeviceDelete(id) {
      // 设备删除
      accountDelete({ id }).then(res => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.postFindPage()
      })
    },

    handleTree(data) {
      // 点击树形结构
      this.queryFormData = { deptId: data.id }
      this.deviceTablePaging = {
        page: 1,
        pagesize: 10
      }
      this.postFindPage()
    },
    // 加载菜单树
    async loadNode(node, resolve) {
      // 加载一级菜单
      if (node.level === 0) {
        const arr = await commonGetDeptTree({ parentId: 0 })
        resolve(arr)
        return false
      }
      const list = await commonGetDeptTree({ parentId: node.data.id })
      resolve(list)
    },
    handleUpdateStatus(id, status) {
      // 更新状态
      this.postUpdateStatus(id, status)
    },
    postUpdateStatus(id, status) {
      // 更新状态接口请求
      accountUpdateStatus({ id, status }).then(() => {
        this.$message.success('操作成功')
        this.postFindPage()
      })
    },
    changeLocation(e) {
      // 改变部门
      // 获取查询部门下拉
      delete this.$refs.TableSearch.formValue.deptId
      selectDeptList({ type: e }).then(val => {
        const res = val.map(e => ({
          key: e.id,
          value: e.name
        }))
        this.queryFormItem.forEach(obj => {
          for (const key in obj) {
            if (obj[key] === 'deptId') {
              this.$set(obj, 'options', res)
            }
          }
        })
      })
    },
    handleCancle() {
      this.dialogVisible = false
      this.$refs.deviceUpdate.$data.accountTypeValue = 0
      this.$refs.deviceUpdate.$data.allCheckedTreeId = []
      this.$refs.deviceUpdate.$data.checkedId = []
      this.$refs.deviceUpdate.$data.checkedName = []
      this.$refs.deviceUpdate.$data.checkedTreeNode = []
      this.$refs.deviceUpdate.$data.innerOptions = []
      this.$refs.deviceUpdate.$data.treeDataC = []
      this.$refs.deviceUpdate.$data.dataRightTypeDisabled = true
      this.$refs.deviceUpdate.$data.addOrEdit = true
    }
  }
}
</script>

<style lang="scss" scoped>
.banner {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  // min-height: calc(100vh - 132px);
  .right {
    min-width: 75%;
    margin-left: 20px;
  }
  .left {
    min-width: 15%;
    // height: calc(100vh - 200px);
    height: 648px;
    /deep/ .el-card__body {
      height: 100%;
      overflow: auto;
    }
  }
}
.app-page {
  min-height: 0;
}
</style>
